import StageScene from "./StageScene"
import Tools from "../Tools"

export default class Bullet extends Laya.Script3D {
  public type: number
  private enemy: Laya.Sprite3D
  private static bulletBoom: Laya.Sprite3D
  private bullet: Laya.Sprite3D
  public props = [
    {
      power: 60,
      speed: 0.2
    },
    {
      power: 80,
      speed: 0.0001
    },
    {
      power: 10,
      speed: 0.1
    }
  ]
  public attack(enemy: Laya.Sprite3D, type) {
    this.enemy = enemy
    this.type = type
    this.bullet = this.owner as Laya.Sprite3D
  }

  onUpdate() {
    if (!this.enemy) return
    if (this.enemy.destroyed) {
      // 敌人被消灭 子弹自毁
      this.destroyeBullet()
    } else {
      // 攻击敌人
      this.bullet.transform.lookAt(this.enemy.transform.position, new Laya.Vector3(0, 1, 0), false)
      // this.bullet.transform.rotate(new Laya.Vector3(0, 180, 0), false, false)
      let movePos = new Laya.Vector3()
      this.bullet.transform.getForward(movePos)
      Laya.Vector3.scale(movePos, this.props[this.type].speed * Laya.timer.delta, movePos)
      this.bullet.transform.translate(movePos, false)
    }
  }

  public destroyeBullet() {
    if (!Bullet.bulletBoom) Bullet.bulletBoom = Laya.loader.getRes('res/atlas/Models/Conventional/BulletBoom.lh')
    // 销毁自身
    let boom = Laya.Sprite3D.instantiate(Bullet.bulletBoom, StageScene.instance.stageScene, false, this.bullet.transform.position)
    Tools.destroy(boom, 300)
    this.bullet.destroy()
  }
}